import { SdkRewardVideoState } from "../SdkConstants"
import SdkBase from "./SdkBase"


export default class SdkOppo extends SdkBase {
    private env: IOppo = window['qg']

    private rewardVideo: IOppoRewardVideo


    public rewardVideoPlay(id: string, cb: (state: number, ret?: any) => void) {
        if (!this.rewardVideo) {
            this.rewardVideo = this.env.createRewardedVideoAd({ adUnitId: id })
            if (!this.rewardVideo) {
                cb(SdkRewardVideoState.PlayError, 'oppo rewardVideo createRewardedVideoAd 失败')
                return
            }
        }


        const loadCall = () => {
            this.rewardVideo.show().
                then(() => cb(SdkRewardVideoState.PlaySuccess)).
                catch(err => console.error('oppo rewardVideo show catch err:' + JSON.stringify(err)))
        }

        const closeCall = (ret: IOppoRewardVideoCloseRet) => {
            if (!ret || ret.isEnded) {
                cb(SdkRewardVideoState.CloseReward)
            } else {
                cb(SdkRewardVideoState.Close)
            }

            this.rewardVideo.offLoad(loadCall)
            this.rewardVideo.offClose(closeCall)
            this.rewardVideo.offError(errorCall)
        }

        const errorCall = (err: any) => {
            cb(SdkRewardVideoState.PlayError, 'oppo rewardVideo onError err:' + JSON.stringify(err))

            this.rewardVideo.offLoad(loadCall)
            this.rewardVideo.offClose(closeCall)
            this.rewardVideo.offError(errorCall)
        }


        this.rewardVideo.onLoad(loadCall)
        this.rewardVideo.onClose(closeCall)
        this.rewardVideo.onError(errorCall)

        this.rewardVideo.load()
    }
}
